
//  LampController.m
//  GBKHOME
//  Created by XMYY-19 on 2017/9/4.
#import "LampController.h"
#import "UIViewController+Category.h"
#import "Masonry.h"
#import "eventAction.h"

@interface LampController ()
@property(nonatomic,assign)BOOL isClick;

@property(nonatomic,assign)int lampStrike;
@property(nonatomic,assign)BOOL isStoped;
@property(nonatomic,assign)dispatch_time_t timer;
@property(nonatomic,strong)dispatch_queue_t queue;
@end

@implementation LampController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
-(id)initWithEquipment:(NewEquipment *)equ
{
    self = [super init];
    if (self)
    {
        self.equipment = equ;
        self.lampStrike = 0;
        self.isStoped = NO;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationTitleView:_equipment.name];
   // self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"mainbg"]];
    UIImage *image =[UIImage imageNamed:@"mainbg"];
    self.view.layer.contents = (id)image.CGImage;
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
    [self loadInitUI];
}

-(void)loadInitUI
{
    self.lampButtonPic =[[UIButton alloc] init];
    if (self.equipment.state.integerValue ==2) {
        [self.lampButtonPic setBackgroundImage:[UIImage imageNamed:@"icon_deng_off"] forState:UIControlStateNormal];
    }else{
        [self.lampButtonPic setBackgroundImage:[UIImage imageNamed:@"icon_deng_on1"] forState:UIControlStateNormal];
    }
    [self.lampButtonPic setAdjustsImageWhenDisabled:NO];
    [self.lampButtonPic setAdjustsImageWhenHighlighted:NO];
    [self.lampButtonPic addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
   
    [self.view addSubview:self.lampButtonPic];
    
    self.tipsLabel =[[UILabel alloc] init];
    self.tipsLabel.text = @"轻触开启";
    self.tipsLabel.textColor =[UIColor colorWithRGBColorByString:@"#9aacc7"];
    self.tipsLabel.font =[UIFont systemFontOfSize:kFONT_SIZE_FROM_PX_VALUE(30)];
    [self.view addSubview:self.tipsLabel];
    
    self.lampSwitch = [[UIButton alloc]init];
    if (self.equipment.state.integerValue ==2) {
        [self.lampSwitch setBackgroundImage:[UIImage imageNamed:@"btn_power_off"] forState:UIControlStateNormal];
    } else {
        [self.lampSwitch setBackgroundImage:[UIImage imageNamed:@"btn_power_on"] forState:UIControlStateNormal];
    }
    [self.lampSwitch addTarget:self action:@selector(switchBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.lampSwitch];
    
    self.brightBtn =[[UIButton alloc] init];
    [self.brightBtn setTitle:@"亮" forState:UIControlStateNormal];
    [self.brightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.brightBtn.titleLabel.font = [UIFont systemFontOfSize:kFONT_SIZE_FROM_PX_VALUE(24)];
    [self.view addSubview:self.brightBtn];
    [self.brightBtn setBackgroundImage:[UIImage imageNamed:@"btn_chang"] forState:UIControlStateNormal];
    self.brightBtn.hidden = NO;
    [self.brightBtn addTarget:self action:@selector(brightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.stopBtn =[[UIButton alloc] init];
    [self.stopBtn setTitle:@"停" forState:UIControlStateNormal];
    [self.stopBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.stopBtn.titleLabel.font = [UIFont systemFontOfSize:kFONT_SIZE_FROM_PX_VALUE(24)];
    [self.view addSubview:self.stopBtn];
    [self.stopBtn setBackgroundImage:[UIImage imageNamed:@"btn_chang"] forState:UIControlStateNormal];
    self.stopBtn.hidden = NO;
    [self.stopBtn addTarget:self action:@selector(stopBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    
    self.darkBtn =[[UIButton alloc] init];
    [self.darkBtn setTitle:@"暗" forState:UIControlStateNormal];
    [self.darkBtn setTitleColor:[UIColor colorWithRGBColorByString:@"#ffffff"] forState:UIControlStateNormal];
    self.darkBtn.titleLabel.font =[UIFont systemFontOfSize:kFONT_SIZE_FROM_PX_VALUE(24)];
    [self.view addSubview:self.darkBtn];
    [self.darkBtn setBackgroundImage:[UIImage imageNamed:@"btn_chang"] forState:UIControlStateNormal];
    self.darkBtn.hidden = NO;
    [self.darkBtn addTarget:self action:@selector(darkBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    
    _mySlider =[[UISlider alloc] init];
    _mySlider.frame =CGRectMake(kFONT_SIZE_FROM_PX_VALUE(104),400,200,50);
    _mySlider.maximumValue =100;
    _mySlider.value =30;
    //左侧滑条背景颜色
    _mySlider.minimumTrackTintColor =[UIColor colorWithRGBColorByString:@"#2ea9dd"];
    //右侧滑条背景颜色
    _mySlider.maximumTrackTintColor =[UIColor colorWithRGBColorByString:@"#17174c"];
    //设置滑块的颜色
    _mySlider.thumbTintColor =[UIColor whiteColor];
    //给滑动条添加事件
    [_mySlider addTarget:self action:@selector(SliderBtn) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_mySlider];
    _mySlider.hidden = YES;
}

#pragma mark - 电器设备开关状态
-(void)btnClick:(UIButton *)sender
{
}

- (void)ctlDeviceEnd:(NSDictionary *)dic
{
    if (self.equipment == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
    NSString *tip = @"";
    BOOL OPEN = [DeviceView deviceStateOn:self.equipment];
    BOOL STATE = !OPEN;
    NSNumber *result = [dic objectForKey:@"result"];
    if (result.integerValue == 0) {
        
        tip = [OperationTip operat:self.equipment.name open:STATE result:YES errorType:ErrorTypeServerReturnFail];
        [self setDeviceOn:STATE];
        
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNet];
    }
    else
    {
        tip = [OperationTip operat:self.equipment.name open:STATE result:NO errorType:ErrorTypeServerReturnFail];
    }
    
    [iToast showTip:tip gravity:iToastGravityBottom];
}

- (void)setDeviceOn:(BOOL)on
{
    if (on) {
        self.equipment.state = kStateON;
    }
    else
    {
        self.equipment.state = kStateOFF;
    }
}

+ (void)ctlDeviceSwithcId:(NSString *)swId name:(NSString *)name OnOff:(BOOL)open target:(id)target end:(SEL)action{
    NSString *order = @"";
    NSString *switchId = swId;
    if (open) {
        order = @"OPEN";
    }
    else
    {
        order = @"CLOSE";
    }
    
    NSString *tipStart = [OperationTip startOperat:open name:name];
    [iToast showTip:tipStart gravity:iToastGravityBottom];
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, order, switchId, sessionId];
    
    [WebServices setShowConnectting:NO];
    
    NSString *errorTip = [OperationTip operat:name open:open result:NO errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"ctlDevice" body:body target:target action:action errorTip:errorTip];
}

-(void)SliderBtn
{
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [_lampButtonPic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kFONT_SIZE_FROM_PX_VALUE(350), kFONT_SIZE_FROM_PX_VALUE(350)));
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(kFONT_SIZE_FROM_PX_VALUE(122));
    }];
    
    [_tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_lampButtonPic.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(kFONT_SIZE_FROM_PX_VALUE(150), kFONT_SIZE_FROM_PX_VALUE(30)));
    }];
    
    [_lampSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_lampButtonPic.mas_bottom).with.offset(kFONT_SIZE_FROM_PX_VALUE(100));
        make.size.mas_offset(CGSizeMake(88,46));
    }];
    
    __block CGFloat btnWidth,btnMargin,btnLeft,btnHeight;
    if (IS_IPAD) {
        btnWidth = 100;
        btnHeight = 45;
        btnMargin = 30;
        btnLeft = (SCREEN_WIDTH -btnWidth*3-btnMargin*2)/2;
    } else {
        btnWidth = 80;
        btnHeight = 45;
        btnMargin = 20;
        btnLeft = (SCREEN_WIDTH -btnWidth*3-btnMargin*2)/2;
    }
    
    [_brightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(btnLeft);
        make.top.equalTo(_lampButtonPic.mas_bottom).with.offset(120);
        make.size.mas_offset(CGSizeMake(btnWidth, btnHeight));
    }];
    
    [_stopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(btnLeft + btnWidth+btnMargin);
        make.top.equalTo(_lampButtonPic.mas_bottom).with.offset(120);
        make.size.mas_offset(CGSizeMake(btnWidth, btnHeight));
    }];
    
    [_darkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(btnLeft + (btnWidth+btnMargin)*2);
        make.top.equalTo(_lampButtonPic.mas_bottom).with.offset(120);
        make.size.mas_offset(CGSizeMake(btnWidth, btnHeight));
    }];
    

}

- (void)switchBtn:(id *)sender{
    BOOL isOpen;
    NSString *switchId = self.equipment.switchId;
    if([self.equipment.state isEqualToString:@"1"])
    {
        isOpen = NO;
        self.equipment.state = @"2";
    } else {
        isOpen = YES;
        self.equipment.state = @"1";
    }
    __weak __typeof(&*self)weakSelf =self;
    [eventAction electricCompantWithOrder:isOpen swtichId:switchId result:^(NSDictionary *dic) {
        __strong __typeof(&*weakSelf)strongSelf = weakSelf;
        [strongSelf ctlDeviceEnd:dic];
    }];
    if(self.isClick)
    {
        [self.lampButtonPic setBackgroundImage:[UIImage imageNamed:@"icon_deng_off"] forState:UIControlStateNormal];
        [self.lampSwitch setBackgroundImage:[UIImage imageNamed:@"btn_power_off"] forState:UIControlStateNormal];
        self.isClick = NO;
    }
    else
    {
        [self.lampButtonPic setBackgroundImage:[UIImage imageNamed:@"icon_deng_on1"] forState:UIControlStateNormal];
        [self.lampSwitch setBackgroundImage:[UIImage imageNamed:@"btn_power_on"] forState:UIControlStateNormal];
        self.isClick = YES;
    }
}

- (void)brightBtnClick:(UIButton *)sender{
    if ([self.equipment.state integerValue] == 1) {
        if (self.isStoped) {
            dispatch_resume(self.timer);
            self.isStoped = NO;
            return;
        }
        [self lightOperat:@"+"];
        NSTimeInterval period = 1.0;
        
        __weak __typeof(&*self)weakSelf =self;
        dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(self.timer, ^{
        __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if (strongSelf.lampStrike == 5) {
                dispatch_suspend(self.timer);
            }
            [strongSelf goBright];
        });
        dispatch_resume(self.timer);
    }
}

- (void)darkBtnClick:(UIButton *)sender{
    if ([self.equipment.state integerValue] == 1) {
        if (self.isStoped) {
            dispatch_resume(self.timer);
            self.isStoped = NO;
            return;
        }
        [self lightOperat:@"-"];
        NSTimeInterval period = 1.0;
        __weak __typeof(&*self)weakSelf =self;
        dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(self.timer, ^{
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if (strongSelf.lampStrike == 1) {
                dispatch_suspend(self.timer);
            }
            [strongSelf goDark];
        });
        dispatch_resume(self.timer);
    }
}

- (void)stopBtnClick:(UIButton *)sender{
    dispatch_suspend(self.timer);
    self.isStoped = YES;
}

- (void)goBright
{
    self.lampStrike++;
    if (self.lampStrike >5) {
        self.lampStrike = 5;
    }
    [self showLampStrike];
}

- (void)goDark
{
    self.lampStrike--;
    if (self.lampStrike <1) {
        self.lampStrike = 1;
    }
    [self showLampStrike];
}

- (void)goStop
{
    [self lightOperat:@"S"];
}

- (void)showLampStrike{
    NSString *strike = [[NSString alloc]initWithFormat:@"icon_deng_on%d",self.lampStrike];
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.lampButtonPic setBackgroundImage:[UIImage imageNamed:strike] forState:UIControlStateNormal];
    });
}

- (void)lightOperat:(NSString *)operat
{
    if([self.equipment.state isEqualToString:kStateOFF])//未电器打开
    {
        NSString *pleaseOpen = NSLocalizedString(@"pleaseOpen", nil);
        [iToast showTip:pleaseOpen gravity:iToastGravityBottom];
        return;
    }
    self.operation = operat;
    NSString *orderName = @"";
    if ([self.operation isEqualToString:@"+"]) {
        orderName = NSLocalizedString(@"bright", nil);
    }
    if ([self.operation isEqualToString:@"S"]) {
        orderName = NSLocalizedString(@"pause", nil);
    }
    if ([self.operation isEqualToString:@"-"]) {
        orderName = NSLocalizedString(@"dark", nil);
    }
    NSString *operatStr = NSLocalizedString(@"operat:", nil);
    NSString *startTip = [operatStr stringByAppendingString:orderName];
    [iToast showTip:startTip gravity:iToastGravityBottom];
    
    NSString *fomate = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *switchId = self.equipment.switchId;
    NSString *sessionId = [LoginController1 sessionID];
    NSString *json = [NSString stringWithFormat:fomate, operat, switchId, sessionId];
    NSString *order = @"regulateRight";
    
    [WebServices setShowConnectting:NO];
    [WebServices requestSynStartOrder:order body:json result:^(NSDictionary *dic) {
        
    }];
}

@end
